#include "util.h"

#include "definitions.h"

#include <sstream>
#include <fcntl.h>

#include <iostream>

void intToString(int num, std::string &str)
{
	std::stringstream out;
	out << num;
	str += out.str();
}

std::string getPathOnlineUsers()
{
	std::string name = TEMP_FOLDER;
	name += ONLINE_USERS_FILE;
	return name;
}



std::string getPathRequests(int userID)
{
	std::string name = TEMP_FOLDER;
	intToString(userID, name);
	name += REQUESTS_FILE_EXTENSION;

	return name;
}



std::string getPathSharedFiles(int userID)
{
	std::string name = TEMP_FOLDER;

	intToString( userID, name );
	name += SHARED_FILE_EXTENSION;

	return name;
}



std::string getPathSharedFilesBitmap(int userID)
{
	std::string name = TEMP_FOLDER;

	intToString( userID, name );
	name += SHARED_FILE_EXTENSION;
	name += BITMAP_FILE_EXTENSION;

	return name;
}



std::string getPathDownload(int ownerID, int clientID, std::string & file)
{
	//para mati
	std::string name = TEMP_FOLDER;

	intToString(ownerID,name);
	name += "_";

	for ( size_t i=0; i<file.size();i++)
	{
		if (file[i] == '/')
			name += '-';
		else
			name += file[i];
	}

	name += "_";
	intToString(clientID,name);
	name += DOWNLOAD_FILE_EXTENSION;

	return name;
}

std::string getPathDownloadedFile(std::string &file)
{
	std::string name = DOWNLOADS_FOLDER;

	unsigned int pos = file.find_last_of('/',file.length());

	if ( pos == std::string::npos )
		pos = 0;
	else
		++pos;

	name += file.substr(pos);

	//checkear que no exista el archivo.. si existe se le agrega un numero al nombre
	int fd = -1;
	int count = 0;
	std::string newName = name;

	while ( (fd = open(newName.c_str(),O_RDONLY, 0777 )) > 0 )
	{
		close(fd);
		++count;

		newName = name;

		std::string num = " (";
		intToString(count,num);
		num += ')';

		pos = newName.find_last_of('.',newName.length());

		if ( pos > newName.length())
			pos = newName.length();

		newName.insert(pos, num);

	}

	return newName;
}

std::string getSemaphoreKeyFile(int ownerID)
{
	std::string file = TEMP_FOLDER;
	intToString(ownerID,file);
	file+= ".semaphore";

	return file;
}


